# -*- coding: utf-8 -*-
# coding=utf-8
from __future__ import print_function, absolute_import, unicode_literals
import sys
import numpy as np
import matplotlib.pyplot as plt
from gm.api import *
import os
import talib
from 掘金3_分钟回测.专用的分析包 import *
from 掘金3_分钟回测.结论下定的包 import *

try:
    import statsmodels.tsa.stattools as ts
except:
    print('请安装statsmodels库')
    sys.exit(-1)

import matplotlib.pyplot as plt
import numpy as np
import matplotlib
from 掘金3_分钟回测.沪铜专用策略 import *


# import 均线策略.品种生成器

def getallvariety():
    "获取所有的期货品种"
    种类 = {

        "INE":
            ["SC", ],  # 原油主力合约
        "SHFE":
            [
                "AG",  # 白银主力合约
                "AL",  # 铝主力合约
                "AU",  # 黄金主力合约
                "BU",  # 沥青主力合约
                "CU",  # 铜主力合约
                "FU",  # 燃油主力合约
                "HC",  # 热轧卷板主力合约
                "NI",  # 镍主力合约
                "PB",  # 铅主力合约
                "RB",  # 螺纹钢主力合约
                "RU",  # 橡胶主力合约
                "SN",  # 锡主力合约
                "SP",  # 纸浆主力合约
                "WR",  # 线材主力合约
                "ZN", ]  # 锌主力合约
    }

    获取次数 = 0
    s = []
    for i in 种类:
        a = [i + '.' + j for j in 种类[i]]
        for k in a:
            # print(k)
            s.append(k)
    print(k)
    return s


# 设置matplotlib正常显示中文和负号
matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 用黑体显示中文
matplotlib.rcParams['axes.unicode_minus'] = False  # 正常显示负号
# 随机生成（10000,）服从正态分布的数据
# data = np.random.randn(10000)


# nowdays = ''
today = 0

Warehouse = [0 for i in range(len(getallvariety()))]


def init(context):
    # 按说这个是初始化
    context.nowdays = ''
    context.goods = ['SHFE.rb1801', 'SHFE.rb1805']
    context.goods = getallvariety()
    # 订阅品种
    subscribe(symbols=context.goods, frequency='60s', count=8001, wait_group=True)

    subscribe(symbols=context.goods, frequency='3600s', count=8001, wait_group=True)
    # close = context.data(symbol=context.goods[0], frequency='60s', count=801, fields='close')['close'].values

    print("美好的一个策略开始了")


def on_bar(context, bars):
    global Warehouse
    now = context.now
    # last_day = get_previous_trading_date('SHFE', now)
    # 获取过去800个60s的收盘价数据
    close = []
    for i in range(len(context.goods)):
        close.append(
            list(context.data(symbol=context.goods[i], frequency='3600s', count=8001,
                              fields='open,high,low,close').values))
    # close_02 = context.data(symbol=context.goods[1], frequency='3600s', count=801, fields='close')['close'].values

    # 每天对数据进行分析eddeeeeeeeeedeee
    if context.nowdays != str(context.now)[:10]:
        # 重新做一次数据分析
        context.nowdays = str(context.now)[:10]

        today = 0

        print('这是新的一天，先分析数据吧！', str(context.now))

    # 所有的数据列表
    print("所有的数据列表")
    data_h_list = []
    for i in range(len(context.goods)):
        data_h_list.append(
            context.data(symbol=context.goods[0], frequency='3600s', count=801, fields='open,high,low,close'))

    # 所有数据的MA指数
    print("所有数据的MA指数")
    MA_h_list = []
    for i in range(len(context.goods)):
        MA_h_list.append(talib.MA(data_h_list['close'], timeperiod=3590))

    # 所有的持仓
    # Warehouse=Warehouse
    for i in range(len(Warehouse)):
        print('当前', context.goods[i])
        if Warehouse[i] == 0:
            # 根据均线数值下单
            if list(data_h_list[i]['close'])[-1] - list(MA_h_list[i])[-1] < -0:
                print('入', context.goods[i])
                Warehouse[i] += 1
            elif list(data_h_list[i]['close'])[-1] - list(MA_h_list[i])[-1] > -0:
                print('出', context.goods[i])
                Warehouse[i] -= 1
        else:
            if Warehouse[i] < 0 and list(data_h_list[i]['close'])[-1] - list(MA_h_list[i])[-1] > -0:
                print('平多')
                Warehouse[i] += 1
            if Warehouse[i] > 0 and list(data_h_list[i]['close'])[-1] - list(MA_h_list[i])[-1] > -0:
                print('平空')
                Warehouse[i] -= 1


# 查看最终的回测结果
def on_backtest_finished(context, indicator):
    print(indicator)


if __name__ == '__main__':
    '''
    strategy_id策略ID,由系统生成
    filename文件名,请与本文件名保持一致
    mode实时模式:MODE_LIVE回测模式:MODE_BACKTEST
    token绑定计算机的ID,可在系统设置-密钥管理中生成
    backtest_start_time回测开始时间
    backtest_end_time回测结束时间
    backtest_adjust股票复权方式不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
    backtest_initial_cash回测初始资金
    backtest_commission_ratio回测佣金比例
    backtest_slippage_ratio回测滑点比例
    '''
    run(strategy_id='80fc12d8-ef58-11e9-89b5-b499baf0193a',
        filename=(os.path.basename(__file__)),
        mode=MODE_BACKTEST,
        token='90be3f863b23ab3c1ef68d1f9b8dc06e4bebb30d',
        backtest_start_time='2017-08-27 08:00:00',
        backtest_end_time='2017-10-01 16:00:00',
        backtest_adjust=ADJUST_PREV,
        backtest_initial_cash=150000,
        backtest_commission_ratio=0.0001,
        backtest_slippage_ratio=0.0001
        )
